import $ from 'jquery'
import {DateFormat} from "../utils/DateFormat"
import {PopToast} from "../utils/PopToast"


let wishList = []

let todoList = []

let $naviPage = $('.navi-page')  // 导航页
let $indicatorUl = $('.indicator ul')  // 切换标识 ul
let $indicatorLis = $indicatorUl.find('li')  // 切换标识 ul > lis
let $todoButton = $('.todo') // 获取代办 button
let $todoInput = $('.todo-input') // 获取代办 input
let $todoListUl = $('.todo-list-ul') // 获取 todoListUl
let $wishInput = $('.wish-input') // 获取愿望 input
let $wishList = $('.wish-list') // 获取愿望 list
let $wishListUl = $('.wish-list-ul') // 获取愿望 listUl
let $wishButton = $('.wish-button') // 获取愿望按钮
let $wishingTab = $('.wishing-tab')  // 获取
let $realizeTab = $('.realize-tab')  // 获取

let $audioWind = $("#audio-wind")[0]  // 获取 wind 音频元素
let $audioLove = $("#audio-love")[0]  // 获取 love 音频元素
let $windmill = $('.windmill') // 获取底部的箭头

// 隐藏 todoInput、wishInput、wishList
$('body').on('click', () => {
    $todoInput.css('display', 'none')
    $wishInput.css('display', 'none')
    $wishList.css('display', 'none')
})

// 决定 document 是否有滚动权限
let documentScrollAuthority = true
$wishListUl.on('mouseover', () => {
    documentScrollAuthority = false
})
$wishListUl.on('mouseleave', () => {
    documentScrollAuthority = true
})

// 添加待办事件
$todoButton.on('click', (event) => {
    event.stopPropagation()
    $todoInput.on('click', (event) => {
        event.stopPropagation()
    })

    $todoInput.css('display', 'inline-block')
    $todoInput.focus()
})


$todoInput.keydown((event) => {
    if (event.code === 'Enter') {
        if ($todoInput.val() === '') return
        if (todoList.length >= 7) {
            PopToast('info', '事情总要一件一件的做嘛，小傻瓜 ~ 😉')
            return
        }

        $.ajax({
            url: 'http://124.221.121.145:9900/todo/add',
            type: 'post',
            // 设置的是请求参数
            data: JSON.stringify({
                todoName: $todoInput.val(),
                todoTime: DateFormat(new Date())
            }),
            contentType: 'application/json',
            dataType: 'json',
            success: function (res) {
                console.log(res);
                $todoInput.val('')
                PopToast('success', '事件添加成功，小傻瓜要加油啦 ~ 👻')
                renderTodoList()
            }
        });

    }
});

// 删除代办事件 todoListItem
$todoListUl.on('click', 'li .cheers svg', function () {
    const $input = $(this).closest('li').find("input")
    const id = $input.val()
    console.log(id)
    $.ajax({
        url: 'http://124.221.121.145:9900/todo/remove',
        type: 'post',
        // 设置的是请求参数
        data: ({
            id: id,
        }),
        dataType: 'json',
        success: function (res) {
            console.log(res);
            renderTodoList()
            PopToast('success', '真是个勤劳的小傻瓜，要劳逸结合哦 ~ 😘')
        }
    });
})


// 渲染 todoList
function renderTodoList() {
    $todoListUl.find('li').remove() // 渲染前移除之前的 todoItem
    $.ajax({
        url: 'http://124.221.121.145:9900/todo/list',
        type: 'get',
        dataType: 'json',
        success: function (res) {
            console.log(res);
            todoList = res.data
            todoList.forEach((item) => {
                let $li = $(`<li class="gauss">
                  <input hidden="hidden" type="number" title="事件id" value="${item.id}"/>
                  <div class="text-time">
                    <div class="text" title="${item.todoName}">${item.todoName}</div>
                    <div class="time">${item.todoTime}</div>
                  </div>
                  <div class="cheers" title="大功告成，干杯 ~">
                    <svg class="icon"><use xlink:href="#icon-jiubei"></use></svg>
                  </div>
                 </li>`)
                $todoListUl.append($li)
            })
        }
    });

}

// 初始化渲染 todoList
renderTodoList()

// 添加小愿望 - wishList
$wishButton.on('click', (event) => {
    event.stopPropagation()
    $wishInput.on('click', (event) => {
        event.stopPropagation()
    })
    $wishList.on('click', (event) => {
        event.stopPropagation()
    })
    $wishInput.css('display', 'inline-block')
    $wishList.css('display', 'inline-block')
    $wishInput.focus()
})
$wishInput.keydown((event) => {
    if (event.code === 'Enter') {
        if ($wishInput.val() === '') return
        let isRepeat = false
        console.log(wishList)
        wishList.map(item => {
            if (item.wishName === $wishInput.val()) {
                isRepeat = true
            }
        })
        if (isRepeat) {
            PopToast('warning', '有啦有啦，这个小愿望已经有啦 ~ 😉')
        } else {
            $.ajax({
                url: 'http://124.221.121.145:9900/wish/add',
                type: 'post',
                // 设置的是请求参数
                data: JSON.stringify({
                    wishName: $wishInput.val(),
                    wishTime: DateFormat(new Date())
                }),
                contentType: 'application/json',
                dataType: 'json',
                success: function (res) {
                    console.log(res);
                    $wishInput.val('')
                    renderWishList()
                    PopToast('success', '添加成功，让我看看我家小傻瓜许的什么愿？ 🧐')
                }
            });
        }
    }
});

// 实现小愿望 wishListItem
$wishListUl.on('click', 'li .heart svg', function () {
    const $input = $(this).closest('li').find("input")
    let id = $input.val();
    console.log("点击的心愿id是" + id)
    $.ajax({
        url: 'http://124.221.121.145:9900/wish/remove',
        type: 'post',
        // 设置的是请求参数
        data: ({
            id: id,
        }),
        dataType: 'json',
        success: function (res) {
            console.log(res);
            renderWishList('wishing')
            PopToast('success', '哦吼吼，实现啦，愿望实现啦 ~ 😍')
        }
    });
})

// 切换愿望 tab - wishing/realize
$wishingTab.on('click', () => {
    $wishingTab.addClass('active').siblings().removeClass("active")
    renderWishList('wishing')
})
$realizeTab.on('click', () => {
    $realizeTab.addClass('active').siblings().removeClass("active")
    renderRealizeList('realize')
})

// 渲染 wishList
function renderWishList(state = 'wishing') {
    $wishListUl.find('li').remove() // 渲染前移除之前的 wishItem

    $.ajax({
        url: 'http://124.221.121.145:9900/wish/list',
        type: 'get',
        dataType: 'json',
        success: function (res) {
            console.log(res);
            wishList = res.data
            let filterWishList = [];
            filterWishList = state === 'wishing' ?
                wishList.filter(item => {
                    return item.isDone === 0
                }) :
                wishList.filter(item => {
                    return item.idDone === 1
                })
            filterWishList.forEach((item) => {
                let $li = $(`<li class="gauss">
              <span class="text" title="${item.wishName}">${item.wishName}</span>
              <div class="heart" title="点击小红心就表示愿望已经实现了哦 ~">
                <svg class="icon"><use xlink:href="#icon-aixin"></use></svg>
              </div>
              <input hidden="hidden" title="事件id"  type="number" value="${item.id}" />
              <input  hidden="hidden" type="text" value="${item.id}" />
            </li>`)
                $wishListUl.append($li)
            })

        }
    });


}

//实现列表
function renderRealizeList(state = 'realize') {
    $wishListUl.find('li').remove()

    $.ajax({
        url: 'http://124.221.121.145:9900/wish/list',
        type: 'get',
        dataType: 'json',
        success: function (res) {
            console.log(res);
            wishList = res.data
            let filterWishList = [];
            filterWishList = state === 'realize' ?
                wishList.filter(item => {
                    return item.isDone === 1
                }) :
                wishList.filter(item => {
                    return item.idDone === 0
                })
            filterWishList.forEach((item) => {
                let $li = $(`<li class="gauss">
              <span class="text" title="${item.wishName}">${item.wishName}</span>
<!--              <div class="heart">-->
<!--                <svg class="icon"><use xlink:href="#icon-duihao"></use></svg>-->
<!--              </div>-->
              <input  hidden="hidden" type="text" value="${item.id}" />
            </li>`)
                $wishListUl.append($li)
            })

        }
    });


}

// 初始化渲染 wishList
renderWishList()

// 背景图片部分
let wallpaperFlag = parseInt(localStorage.getItem("backgroundImageFlag")) || 0  // 标记当前背景图片
let wallpaperArray = [
    {imagePath: require(`../assets/img/wallpaper/yuan.jpg`)},
    {imagePath: require(`../assets/img/wallpaper/harmony_loneliness_lonely.jpg`)},
    {imagePath: require(`../assets/img/wallpaper/Noon.png`)},
    {imagePath: require(`../assets/img/wallpaper/mo.jpg`)},
    {imagePath: require(`../assets/img/wallpaper/schoolGirl.png`)},
    {imagePath: require(`../assets/img/wallpaper/house_path_summer.jpg`)},

]

// 渲染前先获取 localstorage 中标记的壁纸图片
$naviPage.css("backgroundImage", `url(${wallpaperArray[wallpaperFlag].imagePath})`)
// 点击风车 windmill 切换背景图片
$windmill.on('click', () => {
    $windmill.addClass('rotate')
    $windmill.css('pointer-events', 'none')
    $audioWind.play();
    setTimeout(() => {
        $windmill.removeClass('rotate')
        $windmill.css('pointer-events', 'auto')
        $audioWind.ended
    }, 2000)

    wallpaperFlag = wallpaperFlag === 5 ? 0 : wallpaperFlag += 1
    localStorage.setItem("backgroundImageFlag", wallpaperFlag)  // 存储当前壁纸标记到 localStorage
    $naviPage.css("backgroundImage", `url(${wallpaperArray[wallpaperFlag].imagePath})`)
    PopToast('success', '快告诉我这张壁纸好不好看呀 ~ 😎')
})

// 获取当前 active 的 indicator li
let currentIndicator = 0
Array.from($indicatorLis).forEach((item, index) => {
    if (item.className.indexOf('active') > 0)
        currentIndicator = index
})

// 点击 indicator 切换屏幕 0：导航 1：照片墙 2：纪念日
$indicatorUl.on('click', (event) => {
    let clickedIndex = Array.from($indicatorLis).indexOf(event.target)
    if (clickedIndex === -1) return
    $indicatorLis.eq(clickedIndex).addClass('active').siblings().removeClass("active")
    currentIndicator = clickedIndex
    $naviPage.css('margin-top', `${clickedIndex * -100}vh`)

    if (clickedIndex === 2) {
        PopToast('warning', '前方高能预警，单身狗请迅速撤离！ 🤭')
        $audioLove.play()
    } else {
        $audioLove.pause()
    }
})

// 监听鼠标滚轮 切换屏幕 0：导航 1：照片墙 2：纪念日
$(document).on("mousewheel DOMMouseScroll", function (event) {
    var delta = (event.originalEvent.wheelDelta && (event.originalEvent.wheelDelta > 0 ? 1 : -1)) ||  // chrome & ie
        (event.originalEvent.detail && (event.originalEvent.detail > 0 ? -1 : 1))              // firefox

    if (delta > 0 && documentScrollAuthority) {  // 向上滚
        currentIndicator--
        if (currentIndicator >= 0) {
            $naviPage.css('margin-top', `${-currentIndicator * 100}vh`)
            $indicatorLis.eq(currentIndicator).addClass('active').siblings().removeClass("active")
        } else {
            currentIndicator = 0
        }

        // 滑动到非纪念日页 → 停止播放音乐
        if (currentIndicator !== 2) $audioLove.pause()
    } else if (delta < 0 && documentScrollAuthority) { // 向下滚
        if (currentIndicator === 1) PopToast('warning', '前方高能预警，单身狗请迅速撤离！ 🤭')

        currentIndicator++
        if (currentIndicator <= $indicatorLis.length - 1) {
            $naviPage.css('margin-top', `${-currentIndicator * 100}vh`)
            $indicatorLis.eq(currentIndicator).addClass('active').siblings().removeClass("active")
        } else {
            currentIndicator = $indicatorLis.length - 1
        }

        // 滑动到纪念日页 → 播放音乐 + 隐藏 todoList
        if (currentIndicator === 2) $audioLove.play()
    }
})


// 窗口关闭前缓存 localStorage
window.onbeforeunload = function () {
    let newTodoListCache = JSON.stringify(todoList)
    localStorage.setItem('todoListCache', newTodoListCache)

    let newWishListCache = JSON.stringify(wishList)
    localStorage.setItem('wishListCache', newWishListCache)
    //关闭窗口时置公告为true
    localStorage.setItem('isNotice', "true")


}

// kanban part
L2Dwidget.init({
    "display": {"superSample": 2, "width": 200, "height": 400, "position": "right", "hOffset": 0, "vOffset": 0}
});

// statistical script
var _hmt = _hmt || [];
(function () {
    var hm = document.createElement("script");
    hm.src = "https://hm.baidu.com/hm.js?8c000df8ca601a751a83c60449488c8e";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
})();

// 预加载图片
function preloadImages(images) {
    images.forEach(image => {
        const img = new Image();
        img.src = image.imagePath;
    });
}

preloadImages(wallpaperArray);

